package com.wlr.blog.web.common.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wlr.blog.util.common.dto.Result;
import com.wlr.blog.util.common.enums.MailEnum;
import com.wlr.blog.util.common.exception.CustomException;
import com.wlr.blog.web.common.dto.MailRequest;
import com.wlr.blog.web.common.dto.UserDetails;
import com.wlr.blog.web.common.entity.User;
import com.wlr.blog.web.common.mapper.UserMapper;
import com.wlr.blog.web.common.service.SendMailService;
import com.wlr.blog.web.common.service.UserService;
import com.wlr.blog.web.common.utils.CreateJwt;
import com.wlr.blog.web.common.utils.MailUtils;
import com.wlr.blog.web.common.vo.UserVo;
import org.redisson.Redisson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 *
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SendMailService sendMailService;
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Override
    public boolean register(UserVo user) {
        User isExist = userMapper.selectOne(new QueryWrapper<User>()
                .eq("user_name", user.getUserName()));
        int insert;
        String verifyCodeTwo = (String) redisTemplate.opsForValue().get("verifyCode#" + user.getUserName());
        if (StringUtils.isEmpty(verifyCodeTwo)) {
            throw new CustomException("验证码已经过期或已使用");
        } else {
            if (verifyCodeTwo.equals(user.getVerifyCode())) {
                insert = userMapper.insert(user);
                redisTemplate.delete("verifyCode#" + user.getUserName());
            } else {
                throw new CustomException("验证码填写错误，请查看");
            }
        }
        if (Objects.nonNull(isExist)) {
            throw new CustomException("用户已经存在，请直接登录");
        }

        return insert == 1;
    }

    @Override
    public UserDetails login(User user) {
        UserDetails userDetails = new UserDetails();
        User isExist = userMapper.selectOne(new QueryWrapper<User>()
                .eq("user_name", user.getUserName())
                .eq("user_pass", user.getUserPass()));
        if (isExist != null) {
            userDetails.setUserName(user.getUserName());
            userDetails.setId(user.getId());
            String token = CreateJwt.getToken(user);
            userDetails.setToken(token);
            return userDetails;
        }
        return null;
    }
}
